<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="">
                <!-- <el-select v-model="state.searchData.value" class="m-2" placeholder="请选择系统" style="width: 200px;">
                    <el-option v-for="item in state.options2" :key="item.value" :label="item.label" :value="item.value" />
                </el-select> -->
                <!-- <ElInput v-model="state.searchData.keywords" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入菜单名称" :prefix-icon="Search" />
                <ElButton type="primary" :icon="Search" @click="onSearch">
                    查询
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    重置
                </ElButton> -->
                <ElButton type="primary" :icon="Plus" @click="onAdd(null)">
                    新增
                </ElButton>
            </div>
        </div>
        <div class="" style="margin-top: 25px;">
            <Table :columns="allSchemas.tableColumns" :data="dataList" :loading="loading" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
    </ContentWrap>
    <Dialog v-model="dialogVisible1" :title="state.title">
        <el-form ref="ruleFormRef" label-position="top" :model="state.ruleForm" :rules="rules" label-width="120px"
            class="demo-ruleForm" status-icon>
            <el-form-item label="上级栏目" prop="pid">
                <el-cascader v-model="state.ruleForm.pid" :options="state.options2" :props="props" collapse-tags clearable
                    placeholder="请选择上级栏目" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="栏目名称" prop="baseContents">
                <el-input v-model="state.ruleForm.baseContents" placeholder="请输入栏目名称" />
            </el-form-item>
            <el-form-item label="栏目英文(唯一标识)" prop="baseTitle">
                <el-input v-model="state.ruleForm.baseTitle" placeholder="请输入栏目名称" />
            </el-form-item>
            <!-- <el-form-item label="栏目排序" prop="orderNumber">
                <el-input-number min="0" v-model="state.ruleForm.orderNumber" placeholder="请输入显示排序" />
            </el-form-item> -->
            <el-form-item label="栏目类型" prop="baseType">
                <el-select v-model="state.ruleForm.baseType" class="m-2" placeholder="请选择栏目类型">
                    <el-option v-for="item in state.options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="栏目状态" prop="status">
                <el-switch v-model="state.ruleForm.status" class="ml-2"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-value="0"
                    inactive-value="1" />
            </el-form-item>
            <!-- <el-form-item label="栏目配置" prop="baseConfig">
                <el-input type="textarea" :autosize="{ minRows: 2 }" v-model="state.ruleForm.baseConfig"
                    placeholder="请输入栏目配置" />
            </el-form-item> -->
        </el-form>
        <template #footer>
            <div class="flex ">
                <ElButton @click="resetForm(ruleFormRef)">取消</ElButton>
                <ElButton type="primary" :loading="loadingAdd" @click="submitForm(ruleFormRef)">确定
                </ElButton>
            </div>
        </template>
    </Dialog>
</template>
    
<script setup lang="tsx">
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Plus, Refresh, Pointer, Star } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox, ElSwitch } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getTreeList, addbase, editbase, deletebase, getDetail } from "@/api/column/index"
import { useI18n } from '@/hooks/web/useI18n'
import { log } from 'console'
const { t } = useI18n()
const props = {
    checkStrictly: true,
    value: "id",
    label: "baseContents",
    emitPath: false
}
const dialogVisible1 = ref(false)
const loadingAdd = ref(false)
const state = reactive({
    ruleForm: {} as any,
    options2: [] as any,//职位状态下拉框
    searchData: {
        value: "",
        keywords: ""
    },
    react: true,//分页刷新
    title: "新增根级栏目",
    options: [
        {
            label: "父级",
            value: 1
        },
        {
            label: "列表",
            value: 2
        },
        {
            label: "配置",
            value: 3
        },
        {
            label: "单页（输入框）",
            value: 4
        },
        {
            label: "单页（文本编辑框）",
            value: 5
        },
        {
            label: "单页（富文本框）",
            value: 6
        },
        {
            label: "单页（图片）",
            value: 7
        },
        {
            label: "列表（广告）",
            value: 8
        }
    ]
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'baseContents',
        label: t('栏目名称'),
    },
    // {
    //     field: 'weight',
    //     label: t('排序'),
    //     search: {
    //         hidden: true
    //     }
    // },
    {
        field: 'status',
        label: t('栏目状态'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div ><ElSwitch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-value="0" inactive-value="1" v-model={data[0].row.data.status} before-change={() => switchClick(data[0].row)} /></div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('编辑')}
                            </ElButton>
                            {/* <ElButton link type="primary" onClick={() => onAdd(data[0].row)}>
                                {t('添加子模块')}
                            </ElButton> */}
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('删除')}
                            </ElButton>
                        </>
                    )
                }
            }
        }
    }
])
const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        // const { currentPage, pageSize } = tableState
        const res: any = await getTreeList()
        console.log("list数据", res);
        // state.react = false
        state.options2 = res.data
        let array = res.data
        array.forEach(element => {
            traverseTree(element)
        });
        return {
            list: array,
            total: res.total
        }
    }
})
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState

const { getList, getElTableExpose, delList } = tableMethods

// getList()
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})

const { allSchemas } = useCrudSchemas(crudSchemas)
const switchClick = (rows) => {
    console.log(rows);
    let params = rows.data
    params.status = rows.data.status == '0' ? '1' : '0'
    console.log("修改参数", params);
    editbase(params).then((res: any) => {
        ElMessage({
            type: 'success',
            message: `${res.msg}`,
        })
        // getList()
    }).catch((res: any) => {
        ElMessage({
            type: 'error',
            message: `${res.msg}`,
        })
    })
}
// 新增
const onAdd = (item) => {
    if (!item) {
        state.ruleForm = {}
        dialogVisible1.value = true
        state.title = "新增栏目"
    } else {
        state.ruleForm = {
            pid: item.id
        }
        dialogVisible1.value = true
        state.title = "新增子栏目"
    }
}
const action = (row: any) => {
    console.log("编辑", row);
    getMenuDetailApi_(row.id)
    state.title = "编辑栏目"
}
// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.searchData.value = ""
    state.searchData.keywords = ""
    state.react = true
    getList()
}
// 表单
// 校验规则
interface RuleForm {
    baseTitle: string,
    path: string,
    orderNum: string
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    baseContents: [
        { required: true, message: '请填写栏目名称', trigger: 'blur' },
        { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    ],
    // orderNumber: [
    //     { required: true, message: '请输入排序', trigger: 'blur' }
    // ],
    baseTitle: [
        { required: true, message: '请输入栏目英文标识', trigger: 'blur' },
        {
            validator: function (rule, value, callback) {
                if (/[a-zA-z]$/.test(value) == false) {
                    callback(new Error("请输入英文"));
                } else {
                    //校验通过
                    callback();
                }
            },
            trigger: "blur"
        }
    ],
    baseType: [
        { required: true, message: '请选择栏目类型', trigger: 'blur' }
    ],

})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (state.title != "编辑栏目") {
        state.ruleForm.orderNumber=9999
    }
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (state.title != "编辑栏目") {
                state.ruleForm.pid=state.ruleForm.pid?state.ruleForm.pid:0
                addbase(state.ruleForm).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            } else {
                editbase(state.ruleForm).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            }

            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible1.value = false
    formEl.resetFields()
}
const delData = (row: any) => {
    ElMessageBox.confirm('确认删除该栏目？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        deletebase(row.id).then((res: any) => {
            getList()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })


}
// const getTreeselectApi_ = async () => {
//     await getTreeselectApi({}).then((res: any) => {
//         console.log(res.data);
//         state.options2 = res.data
//     })
// }

// getTreeselectApi_()
function traverseTree(node) {
    node.data.status=node.data.status.toString()
    if (node.children && node.children.length > 0) {
        for (let child of node.children) {
            traverseTree(child); // 递归遍历子节点  
        }
    }
}
const getMenuDetailApi_ = async (params) => {
    await getDetail(params).then((res: any) => {
        console.log("栏目详情:", res.data);
        state.ruleForm = res.data
        state.ruleForm.status = state.ruleForm.status.toString()

        dialogVisible1.value = true
    })
}
</script>
    
<style lang="less" scoped></style>